import { approvalPendingInfoApi } from "@/api/financialManagement/payableManagement/paymentApproval";
import { computed, reactive, Ref, ref } from "vue";

export default function InitHook(state: { passData: Ref<PaymentApproval.ApprovalListRow> }) {
  const { passData } = state;
  const applyCostList = ref<Array<PaymentApproval.ApplyCostInfo>>([]);
  const formState = reactive<PaymentApproval.PayableApplyInfo>({
    id: "",
    paymentAmount: 0,
    paymentDescription: "",
    applyResult: "",
    applyPaymentRes: []
  });
  const customerBillRef = ref<any>(null);
  const selectMap = ref<Base.GeneraDataType>({});
  const loading = ref<boolean>(false);
  const init = () => {
    loading.value = true;
    return approvalPendingInfoApi(passData.value.applyNo)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          Object.assign(formState, data);
        }
      })
      .finally(() => (loading.value = false));
  };
  const drawerOpts = reactive<Base.DrawerOpts>({
    title: "",
    width: "",
    visible: false,
    component: "",
    type: 0
  });
  const dialogOpts = reactive<Base.DialogOpts>({
    title: "",
    width: "",
    visible: false,
    component: "",
    type: 0
  });
  // 已选未核销金额
  const selectUnchargeOff = computed<string>(() => {
    const result = [];
    for (const key in selectMap.value) {
      const source = selectMap.value[key].map((t: any) => Number(t.payableAmountSum) || 0);
      result.push(...source);
    }
    return result.reduce((a: number, b: number) => (a * 100 + b * 100) / 100, 0).toFixed(2);
  });
  return {
    customerBillRef,
    init,
    loading,
    drawerOpts,
    dialogOpts,
    formState,
    applyCostList,
    selectMap,
    selectUnchargeOff
  };
}
